import {saveAs} from 'file-saver';
import {request} from './index';
import {MessagePlugin} from "tdesign-vue-next";

// 严重是否为Blob数据
const isBlobData = async (data) => {
    try {
        const text = await data.text();
        JSON.parse(text);
        return false;
    } catch (error) {
        return true;
    }
}

export function download(url, params, filename) {
    return request.post({url, data: params, responseType: 'blob'}).then(async (data) => {
        const isLogin = await isBlobData(data);
        if (isLogin) { // 如果是Blob数据
            const blob = new Blob([data], {type: "application/vnd.ms-excel"}); // 第二个参数为下载的文件的类型
            saveAs(blob, filename);// 调用方法下载
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode.default;
            MessagePlugin.error(errMsg)
        }
    }).catch((r) => {
        console.error(r);
        MessagePlugin.error('下载文件出现错误')
    });
}
